<?php

namespace app\merchant\job;

use app\common\controller\Platurl;
use app\common\model\Agent;
use app\common\model\CardFans;
use app\common\model\CardGeneral;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\System;
use app\common\model\WxOpen;
use think\Queue;
use think\queue\Job;
use think\Session;
use Wechat\Wxobjopen;

class Stati
{

    public function fire(Job $job, $data)
    {
        $isJobDone = $this->task_tpl_stati($data);
        $job->delete();

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
            return '完成';
        } else {
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                print("<warn>任务已完成3次!" . "</warn>\n");
                $job->delete();
                // 也可以重新发布这个任务
                //print("<info>Hello Jobmach will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }



    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */


    //群发模版消息
    public function task_tpl_stati($data)
    {
//        file_put_contents('/data2/html/payos/test.txt', 'stati-1' . json_encode($data,JSON_UNESCAPED_UNICODE), FILE_APPEND);
        //初始化微信类
        if (isset($data['openid'])) {
            $Platurl = new Platurl();
            $options = $Platurl->getagenttplmsg($data['mid']);
//            $options = $this->option($wx_open_id);
            $weObj = new Wxobjopen($options);
            //模板ID
//            $OpenTemplate = new OpenTemplate();
            $templateid = $Platurl->getagenttplid($data['mid']);
            $template['touser'] = $data['openid'];
            $template['template_id'] = $templateid;
            $template['url'] = '';
            $template['topcolor'] = "#7B68EE";
            $template['data']['first'] = ['value' => '请查收昨日会员卡运营数据', 'color' => "#743A3A"];
            $template['data']['keyword1'] = ['value' => $data['keyword1'], 'color' => '#000'];
            $template['data']['keyword2'] = ['value' => date("Y-m-d H:i:s", time()), 'color' => '#FF0000'];
            $template['data']['remark'] = ['value' => $data['remark'], 'color' => '#000'];
            //发送
//            file_put_contents('/data2/html/payos/test.txt', 'stati-2' . json_encode($template,JSON_UNESCAPED_UNICODE), FILE_APPEND);
            $res = $weObj->sendTemplateMessage($template);
//            file_put_contents('/data2/html/payos/test.txt', 'stati-3' . json_encode($res,JSON_UNESCAPED_UNICODE), FILE_APPEND);
//            file_put_contents('/data2/html/payos/exelog/sendstati/' . date("Y-m-d") . '.txt',  'get-' . json_encode($template, JSON_UNESCAPED_UNICODE).PHP_EOL, FILE_APPEND);
            return $res;
        }
    }

    public function failed($data)
    {


    }

    public function get_open_id()
    {
        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');
        return $wx_open_id;
    }

    public function getmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    public function option($wx_open_id)
    {

        $System = new System();
        $WxOpen = new WxOpen();
        $Agent=new Agent();
//        $config = $System->where(['id' => 1])->find();
        $users = $WxOpen->where(['id' => $wx_open_id])->find();
        $config=$Agent->where(array('wx_open_id'=>$wx_open_id))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }


    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent=new Agent();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo= $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();//
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();//

        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}
